<template>
  <div class="app-container">
    <el-row>
      <el-button
        type="success"
        size="mini"
        v-show="activeName!='WEBHOOK'"
        style="float:right;"
        icon="el-icon-plus"
        @click="handleAddChannel()"
      >添加通道
      </el-button>
      <el-button
        type="success"
        size="mini"
        v-show="activeName==='WEBHOOK'"
        style="float:right;"
        icon="el-icon-plus"
        @click="handleAddWebhookFun()"
      >创建Webhook
      </el-button>
    </el-row>
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="短信" name="TEXT_MSG">
        <div v-for="template in templateList">
          <el-row :gutter="10" class="mb8">
            <el-col :span="3" class="head-content">
              <img src="../../../assets/images/jiguang.png" class="index-img">
              <h3>{{ template.channelServiceName }}</h3>
            </el-col>
            <el-col :span="1.5" style="float: right">
              <el-button
                type="info"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="handleCreateFun(template)"
                v-hasPermi="['system:user:import']"
              >创建账号
              </el-button>
            </el-col>
          </el-row>
          <el-table v-loading="loading" :data="pushConfigList[template.channelServiceCode]" @selection-change="handleSelectionChange">
            <el-table-column type="index" label="编号" width="55" align="center"/>
            <el-table-column label="账号名称" align="center" prop="channelName"></el-table-column>
            <el-table-column label="创建人" align="center" prop="createBy"/>
            <el-table-column label="创建时间" align="center" prop="createTime"/>
            <el-table-column label="编辑人" align="center" prop="updateBy"/>
            <el-table-column label="最近编辑时间" align="center" prop="updateTime"/>
            <el-table-column label="操作" width="300" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.status"
                  active-value="Y"
                  inactive-value="N"
                  @change="handleStatusChange(scope.row)"
                ></el-switch>
                {{ scope.row.status === 'Y' ? '启用' : '停用' }}
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleTestFun(scope.row)"
                  v-hasPermi="['config:channel:edit']"
                >测试发送
                </el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['config:channel:edit']"
                >编辑
                </el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['config:channel:remove']"
                >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
      <el-tab-pane label="APP推送" name="PUSH">
        <div v-for="template in templateList">
          <el-row :gutter="10" class="mb8">
            <el-col :span="3" class="head-content">
              <img src="../../../assets/images/jiguang.png" class="index-img">
              <h3>{{ template.channelServiceName }}</h3>
            </el-col>
            <el-col :span="1.5" style="float: right">
              <el-button
                type="success"
                plain
                icon="el-icon-delete"
                size="mini"
                @click="handleUpdate"
                v-hasPermi="['system:user:edit']"
              >删除通道
              </el-button>
            </el-col>
            <el-col :span="1.5" style="float: right">
              <el-button
                type="info"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="handleCreateFun(template)"
              >创建账号
              </el-button>
            </el-col>
          </el-row>
          <el-table v-loading="loading" :data="pushConfigList[template.channelServiceCode]" @selection-change="handleSelectionChange">
            <el-table-column type="index" label="编号" width="55" align="center"/>
            <el-table-column label="账号名称" align="center" prop="channelName"></el-table-column>
            <el-table-column label="创建人" align="center" prop="createBy"/>
            <el-table-column label="创建时间" align="center" prop="createTime"/>
            <el-table-column label="编辑人" align="center" prop="updateBy"/>
            <el-table-column label="最近编辑时间" align="center" prop="updateTime"/>
            <el-table-column label="操作" width="300" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.status"
                  active-value="Y"
                  inactive-value="N"
                  @change="handleStatusChange(scope.row)"
                ></el-switch>
                {{ scope.row.status === 'Y' ? '启用' : '停用' }}
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleTestFun(scope.row)"
                  v-hasPermi="['config:channel:edit']"
                >测试发送
                </el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['config:channel:edit']"
                >编辑
                </el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['config:channel:remove']"
                >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
      <el-tab-pane label="Webhook" name="WEBHOOK">
        <el-table v-loading="loading" :data="channelList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column label="Webhook 名称" align="center" prop="name"></el-table-column>
          <el-table-column label="创建人" align="center" prop="orderNum"/>
          <el-table-column label="创建时间" align="center" prop="orderNum"/>
          <el-table-column label="编辑人" align="center" prop="orderNum"/>
          <el-table-column label="最近编辑时间" align="center" prop="orderNum"/>
          <el-table-column label="操作" width="300" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.status"
                active-value="0"
                inactive-value="1"
                @change="handleStatusChange(scope.row)"
              ></el-switch>
              {{ scope.row.status === 1 ? '启用' : '停用' }}
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleTestFun(scope.row)"
                v-hasPermi="['config:channel:edit']"
              >测试发送
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['config:channel:edit']"
              >编辑
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['config:channel:remove']"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="弹窗" name="fourth">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              @click="showType=1"
            >自定义跳转链接管理
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              @click="showType=2"
            >弹窗自定义参数管理
            </el-button>
          </el-col>
        </el-row>
        <el-card class="panel-content" v-show="showType===1">
          <el-row>
            <el-col :span="24">
              <el-row class="row-content">
                <h3><img src="../../../assets/images/apple-one.png" class="index-img" width="30" height="30"/>iOS
                  平台自定义链接</h3>
              </el-row>
              <el-row style="text-align: center;margin-top:20px;">
                <img src="../../../assets/images/default.svg" class="index-img">
              </el-row>
              <el-row class="row-text">
                <h3>未设置自定义链接，点击右上角按钮进行添加</h3>
              </el-row>
            </el-col>
          </el-row>
        </el-card>
        <el-card class="panel-content" v-show="showType===1">
          <el-row>
            <el-col :span="24">
              <el-row class="row-content">
                <h3><img src="../../../assets/images/android.png" class="index-img" width="30" height="30"/>Android
                  平台自定义链接</h3>
              </el-row>
              <el-row style="text-align: center;margin-top:20px;">
                <img src="../../../assets/images/default.svg" class="index-img">
              </el-row>
              <el-row class="row-text">
                <h3>未设置自定义链接，点击右上角按钮进行添加</h3>
              </el-row>
            </el-col>
          </el-row>
        </el-card>

        <el-card class="panel-content" v-show="showType===1">
          <el-row>
            <el-col :span="24">
              <el-row class="row-content">
                <h3><img src="../../../assets/images/copy-link.png" class="index-img" width="30" height="30"/>H5 平台自定义链接
                </h3>
              </el-row>
              <el-row style="text-align: center;margin-top:20px;">
                <img src="../../../assets/images/default.svg" class="index-img">
              </el-row>
              <el-row class="row-text">
                <h3>未设置自定义链接，点击右上角按钮进行添加</h3>
              </el-row>
            </el-col>
          </el-row>
        </el-card>

        <el-card class="panel-content" v-show="showType===1">
          <el-row>
            <el-col :span="24">
              <el-row class="row-content">
                <h3><img src="../../../assets/images/weixin-mini.png" class="index-img" width="30" height="30"/>小程序自定义链接
                </h3>
              </el-row>
              <el-row style="text-align: center;margin-top:20px;">
                <img src="../../../assets/images/default.svg" class="index-img">
              </el-row>
              <el-row class="row-text">
                <h3>未设置自定义链接，点击右上角按钮进行添加</h3>
              </el-row>
            </el-col>
          </el-row>
        </el-card>


        <el-table v-loading="loading" v-show="showType===2" :data="channelList"
                  @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column label="参数名称" align="center" prop="name"></el-table-column>
          <el-table-column label="创建人" align="center" prop="orderNum"/>
          <el-table-column label="创建时间" align="center" prop="orderNum"/>
          <el-table-column label="编辑人" align="center" prop="orderNum"/>
          <el-table-column label="最近编辑时间" align="center" prop="orderNum"/>
          <el-table-column label="操作" width="300" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.status"
                active-value="0"
                inactive-value="1"
                @change="handleStatusChange(scope.row)"
              ></el-switch>
              {{ scope.row.status === 1 ? '启用' : '停用' }}
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['config:channel:edit']"
              >测试发送
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['config:channel:edit']"
              >编辑
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['config:channel:remove']"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>

    </el-tabs>


    <!-- 添加或修改推送通道管理对话框 -->
    <el-dialog :title="title" :visible.sync="channelOpen" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="选择通道" prop="isPreset">
          <el-select v-model="form.channelConfigId" placeholder="请选择通道预制类型">
            <el-option-group
              v-for="group in chanelconfigList"
              :key="group.label"
              :label="group.label">
              <el-option
                v-for="item in group.options"
                :key="item.id"
                :label="item.channelServiceName"
                :value="item.id">
              </el-option>
            </el-option-group>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改推送通道配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="850px" append-to-body>
      <el-form ref="configFrom" :model="configFrom" :rules="rules" label-width="110px">
        <el-form-item label="通道名称" prop="channelName">
          <el-input v-model="configFrom.channelName" placeholder="请输入通道名称" />
        </el-form-item>
        <el-form-item label="配置参数JSON" prop="paramJson">
          <el-input v-model="configFrom.paramJson" type="textarea" rows="10" placeholder="请输入配置参数JSON" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="configFrom.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="是否可用">
          <el-radio-group v-model="configFrom.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitConfigForm">确 定</el-button>
        <el-button @click="cancelFun">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="发送测试" :visible.sync="testOpen" width="650px" append-to-body>
      <el-form ref="testFrom" :model="testFrom" :rules="rules" label-width="110px">
        <el-form-item label="模板ID" prop="channelName">
          <el-input v-model="testFrom.templateId" placeholder="请输入模板ID" />
        </el-form-item>
        <el-form-item>
          <el-button
            type="success"
            size="mini"
            style="float:right;"
            icon="el-icon-plus"
            @click="handleParamFun"
          >添加参数
          </el-button>
        </el-form-item>
        <el-table :data="paramsList">
          <el-table-column type="index" label="编号" width="55" align="center"/>
          <el-table-column label="参数名称" align="center" prop="paramName">
            <template slot-scope="scope">
              <el-input v-model="scope.row.paramName"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="参数值" align="center" prop="paramValue">
            <template slot-scope="scope">
             <el-input v-model="scope.row.paramValue"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="60" align="center">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDeleteParam(scope.row)"
                v-hasPermi="['config:channel:remove']"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitTestForm">确 定</el-button>
        <el-button @click="testcancelFun">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listChannel,
  getChannel,
  delChannel,
  addChannel,
  updateChannel,
  exportChannel,
  addChannelTemplate
} from "@/api/config/channel";
import {listAllChanelconfig, listChanelconfig} from "@/api/operate/chanelconfig";
import {listChannelTemplateByType} from "@/api/operate/channelTemplate";
import {addPushconfig, listPushconfigGroup, testPushSend, updatePushconfig} from "@/api/operate/pushconfig";
import {delPushconfig, getPushconfig} from "@/api/baseconfig/pushconfig";

export default {
  name: "channel",
  components: {},
  data() {
    return {
      // 遮罩层
      showType: 1,
      activeName: 'TEXT_MSG',
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 触达通道表格数据
      channelList: [],
      pushConfigList: {},
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否启用字典
      statusOptions: [],
      channelTypeOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        status: undefined,
      },
      channelOpen: false,
      // 通道预制类型字典
      chanelconfigList: [],
      templateList: [],
      // 表单参数
      form: {},
      configFrom: {
        id:undefined,
        channelName:undefined,
        paramJson:undefined,
        description:undefined,
        status:undefined,
        channelType:undefined,
        channelServiceCode:undefined,
        channelServiceName:undefined
      },
      testOpen:false,
      paramsList:[],
      currentAccount:{},
      testFrom:{},
      // 表单校验
      rules: {}
    };
  },
  created() {
    this.handleClick();
    this.getChannelConfigList();
    this.getList();
    this.getDicts("sys_yes_no").then(response => {
      this.statusOptions = response.data;
      this.deletedOptions = response.data;
      this.isInUseOptions = response.data;
    });
    this.getDicts("sys_push_channel_type").then(response => {
      this.isPresetOptions = response.data;
    });
    this.getDicts("sys_push_content_type").then(response => {
      this.channelTypeOptions = response.data;
      this.channelTypeOptions = response.data;
    });
  },
  methods: {
    /** 查询触达通道列表 */
    getList() {
      this.loading = true;
      listPushconfigGroup(this.queryParams).then(response => {
        this.pushConfigList = response.data;
        this.loading = false;
      });
    },

    getChannelConfigList() {
      let configparam = {
        pushType: this.activeName
      };
      listAllChanelconfig(configparam).then(response => {
        this.chanelconfigList = response.data;
      });
    },
    handleClick() {
      let params = {
        pushType: this.activeName
      };
      this.loading = true;
      listChannelTemplateByType(params).then(response => {
        this.templateList = response.data;
        this.loading = false;
      });
    },
    // 是否启用字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 取消按钮
    cancel() {
      this.channelOpen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        channelConfigId: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加触达通道";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getPushconfig(id).then(response => {
        this.configFrom = response.data;
        this.open = true;
        this.title = "修改账号信息";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.pushType = this.activeName;
          addChannelTemplate(this.form).then(response => {
            if (response.code === 200) {
              this.msgSuccess("新增成功");
              this.channelOpen = false;
              this.getList();
            } else {
              this.msgError(response.msg);
            }
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除触达通道编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delPushconfig(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(function () {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有触达通道数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return exportChannel(queryParams);
      }).then(response => {
        this.download(response.msg);
      }).catch(function () {
      });
    },
    handleStatusChange(row) {
      let str='';
      let currStatus='';
      if(row.status==='Y'){
        str='停用';
        currStatus='Y';
      }else{
        str='启用';
        currStatus='N';
      }
      const ids = row.id || this.ids;
      this.$confirm('是否确认'+str+'通道编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        let param={
          id:row.id,
          status:currStatus
        };
        return updatePushconfig(param);
      }).then(() => {
        this.getList();
        this.msgSuccess("操作成功");
      }).catch(function () {
      });
    },

    handleAddChannel() {
      this.getChannelConfigList();
      this.channelOpen = true;
    },
    handleCreateFun(template){
      this.open=true;
      console.log(template);
      this.configFrom.channelType=template.pushType;
      this.configFrom.channelServiceCode=template.channelServiceCode;
      this.configFrom.channelServiceName=template.channelServiceName;
      this.configFrom.paramJson=template.paramJson;
    } ,
    cancelFun(){
      this.open=false;
      this.resetFun();
    },
    resetFun(){
      this.configFrom= {
        id:undefined,
          channelName:undefined,
          paramJson:undefined,
          description:undefined,
          status:undefined,
          channelType:undefined,
          channelServiceCode:undefined,
          channelServiceName:undefined
      };
    },
    submitConfigForm(){
      this.$refs["configFrom"].validate(valid => {
        if (valid) {
          if (this.configFrom.id != null) {
            updatePushconfig(this.configFrom).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPushconfig(this.configFrom).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleAddWebhookFun(){

    },
    handleTestFun(row){
      this.testOpen=true;
      this.currentAccount=row;
    },
    testcancelFun(){
      this.testOpen=false;
    },
    handleParamFun(){
      let param={
        paramName:'',
        paramValue:''
      };
      this.paramsList.push(param);
    },
    handleDeleteParam(row){
      let index=this.paramsList.findIndex(item=>item.paramName=row.paramName);
      this.paramsList.splice(index,1);
    },
    submitTestForm(){
      let testParam={
        templateId:this.testFrom.templateId,
        currentAccount:this.currentAccount,
        paramJson:this.paramsList
      }
      let requestJson=JSON.stringify(testParam);
      testPushSend({requestJson:requestJson}).then(response => {
        this.msgSuccess("发送成功");
        this.testOpen = false;
      });
    }
  }
};
</script>
<style rel="stylesheet/scss" lang="scss">
.app-container {
  background: #f7f9fa;
  padding: 20px;
}

.head-content {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding: 13px 0;

  .index-img {
    border: 1px solid #d3dce6;
    border-radius: 50%;
    width: 30px;
    height: 30px;
    display: flex;
    justify-content: center;
    align-items: center;
    overflow: hidden;
  }

  h3 {
    font-size: 16px;
    font-family: PingFangSC-Medium;
    font-weight: 500;
    padding-left: 10px;
    color: #1f2d3d;
    line-height: 22px;
    max-width: 250px;
    margin: 0;
  }
}

.panel-content {
  box-shadow: 2px 0 7px 0 rgb(153 170 192 / 17%);
  margin-bottom: 14px;
}

.row-content {
  justify-content: space-between;
  border-bottom: 1px solid #e9f0f7;
  padding: 0 16px;
  background: #fff;

  h3 {
    line-height: 34px;

    img {
      margin-right: 10px;
    }
  }
}

.row-text {
  text-align: center;
  font-size: 16px;
  color: #99a9bf;
  line-height: 28px;
}
</style>
